use futures::{SinkExt, StreamExt};
use std::io::Error;
use tokio::net::TcpStream;
use tokio_util::codec::{Framed, LinesCodec};

#[derive(Debug)]
pub struct Connection {
    pub framed: Framed<TcpStream, LinesCodec>,
}

impl Connection {
    pub fn new(stream: TcpStream) -> Self {
        Connection {
            framed: Framed::new(stream, LinesCodec::new()),
        }
    }

    pub async fn read_message(&mut self) -> Result<String, Error> {
        let line = match self.framed.next().await {
            Some(Ok(msg)) => msg,
            _ => {
                return Ok("None".to_owned());
            }
        };
        println!("line {}", line);
        Ok(line)
    }

    pub async fn write_message(&mut self, msg: &str) -> Result<(), Error> {
        let _ = self.framed.send(msg).await;
        Ok(())
    }
}
